﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Xml;
using GMusicBox.Core;
using GMusicBox.Core.Setting;

namespace GMusicBox
{
    public partial class frmImportConfig : Form
    {
        public frmImportConfig()
        {
            InitializeComponent();
            this.TopMost = Program.TopMost;
            this.Opacity = Program.Opacity;
        }

        internal MusicList ml = null;

        private void button1_Click(object sender, EventArgs e)
        {
            button1.Enabled = false;
            bool ret = false;
            if (!Directory.Exists(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\GMusicBox")) ret = true;
            else if (!File.Exists(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\GMusicBox\\Config.xml")) ret = true;

            if (ret)
            {
                if (VTaskDialog.CanUseTankDialog())
                    VTaskDialog.ShowTaskDialog("没有找到谷歌音乐盒2.x的配置文件，导入无法继续。", "提示", "找不到配置文件", VTaskDialog.TaskDialogButton.OK, VTaskDialog.TaskDialogIcon.Warning);
                else MessageBox.Show("没有找到谷歌音乐盒2.x的配置文件，导入无法继续。", "找不到配置文件", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            if (!File.Exists(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\GMusicBox\\Playlist.xml"))
            {
                if (VTaskDialog.CanUseTankDialog())
                    VTaskDialog.ShowTaskDialog("没有找到谷歌音乐盒2.x的播放列表文件，将不会导入播放列表。", "提示", "找不到播放列表", VTaskDialog.TaskDialogButton.OK, VTaskDialog.TaskDialogIcon.Warning);
                else MessageBox.Show("没有找到谷歌音乐盒2.x的播放列表文件，将不会导入播放列表。", "找不到播放列表", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }

            backgroundWorker1.RunWorkerAsync(File.Exists(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\GMusicBox\\Playlist.xml"));
        }

        private string GetOldKeywordSet(string s1, string s2)
        {
            HotKey.KeyFlags k = (HotKey.KeyFlags)(int.Parse(s1));
            string ks = k.ToString();
            string result = "";
            result = (ks.IndexOf("MOD_CONTROL") != -1).ToString();
            result += "," + (ks.IndexOf("MOD_SHIFT") != -1).ToString();
            result += "," + (ks.IndexOf("MOD_ALT") != -1).ToString();
            result += "," + s2;
            return result;
        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            Settings s = new Settings(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\GMusicBox\\Config.xml");
            MainSetting.LoopMode = int.Parse(s["Mode"]);
            Settings s1 = new Settings(Settings.SettingSavePath + "\\Config\\Configs\\Main.xml");
            s1["ForMode"] = s["Mode"];
            s1["Volume"] = s["Volume"];
            s1.WriteAllSettings();
            backgroundWorker1.ReportProgress(25);

            s1 = new Settings(Settings.SettingSavePath + "\\Config\\Configs\\Main.xml");
            s1["TopMose"] = s["TopMost"];
            s1["ShowNowPlaying"] = s["MusicTip"];
            s1["AutoStart"] = s["AutoPlay"];
            s1["SearchCount"] = s["SongNums"];
            if (Convert.ToBoolean(s["ShowCloseMsg"])) s1["CloseEvent"] = "0";
            else s1["CloseEvent"] = (int.Parse(s["CloseWay"]) + 1).ToString();

            string hotkeys = "";
            for (int i = 0; i < 5; i++) hotkeys += GetOldKeywordSet(s1["Hotkey_Mod" + i.ToString()], s1["Hotkey_Main" + i.ToString()]) + "|";
            hotkeys = hotkeys.Substring(0, hotkeys.Length - 1);
            s["HotKey"] = hotkeys;
            s1.WriteAllSettings();
            backgroundWorker1.ReportProgress(50);

            ml = new MusicList("", textBox1.Text);
            if ((bool)e.Argument)
            {
            //    XmlDocument xd = new XmlDocument();
            //    xd.Load(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\GMusicBox\\Playlist.xml");
            //    XmlNodeReader xnr = new XmlNodeReader(xd);
                
            //    bool beginWrite = false, beginwrite = false;
            //    int lastindex = -1;
            //    while (xnr.Read())
            //    {
            //        if (xnr.NodeType == XmlNodeType.Element)
            //        {
            //            if (xnr.Name == "song")
            //            {
            //                beginWrite = true;
            //                lastindex++;
            //                mbi.Songs.Add(new MusicBasicInfo());
            //                continue;
            //            }
            //            else if (xnr.Name == "listname")
            //            {
            //                beginwrite = true;
            //                continue;
            //            }

            //            if (beginWrite) mbi.MusicBasicInfos[lastindex].BeginWrite(xnr.Name.Trim());
            //        }
            //        else if (xnr.NodeType == XmlNodeType.Text)
            //        {
            //            if (beginWrite) mbi.MusicBasicInfos[lastindex].WriteBegan(xnr.Value.Trim());
            //            if (beginwrite) mbi = new MusicListInfo(xnr.Value.ToString());
            //        }
            //    }
            //    xnr.Close();
                ml.Songs.AddRange(Song.GetSongList(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\GMusic\\Playlist.xml"));
            }
            backgroundWorker1.ReportProgress(75);

            if (checkBox1.Checked)
            {
                for (int i = 0; i < ml.Songs.Count; i++)
                {
                    ml[i] = Song.GetSongList("http://www.google.cn/music/song?id=" + ml[i].Id + "&output=xml")[0];
                    backgroundWorker1.ReportProgress((int)(25.0 / ml.Songs.Count * (i + 1)) + 75);
                }
            }
            backgroundWorker1.ReportProgress(100);
        }

        private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            progressBar1.Value = e.ProgressPercentage;
        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            button2.DialogResult = DialogResult.OK;
            if (VTaskDialog.CanUseTankDialog())
                VTaskDialog.ShowTaskDialog("已成功导入谷歌音乐盒2.x的配置。", "提示", "导入成功", VTaskDialog.TaskDialogButton.OK, VTaskDialog.TaskDialogIcon.Information);
            else MessageBox.Show("已成功导入谷歌音乐盒2.x的配置。", "找不到配置文件", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        private void button2_Click(object sender, EventArgs e)
        {
            this.Close();
        }
    }
}
